package com.mavenq.fly.test.cglib;


import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibDemo {


    public static void main(String[] args) {
        UserService target = new UserService();

        // 通过cglib技术
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(UserService.class);

        // 定义额外逻辑，也就是代理逻辑
        enhancer.setCallbacks(new Callback[]{
                new MethodInterceptor() {
                    @Override
                    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                        System.out.println("before...");
                        Object result = methodProxy.invoke(target, objects);
                        System.out.println("after...");
                        return result;
                    }
                }
        });
        // 动态代理所创建出来的UserService对象
        UserService userService = (UserService) enhancer.create();
        // 执行这个userService的test方法时，就会额外会执行一些其他逻辑
        userService.test();


        // 通过cglib技术
        Enhancer enhancer1 = new Enhancer();
        enhancer1.setSuperclass(UserService.class);

        // 定义额外逻辑，也就是代理逻辑
        enhancer1.setCallbacks(new Callback[]{
                new MethodInterceptor() {
                    @Override
                    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                        System.out.println("111...");
                        Object result = methodProxy.invoke(target, objects);
                        System.out.println("222...");
                        return result;
                    }
                }
        });
        // 动态代理所创建出来的UserService对象
        UserService userService1 = (UserService) enhancer1.create();
        // 执行这个userService的test方法时，就会额外会执行一些其他逻辑
        userService1.test();
    }


}
